// js逻辑
// 抽出逻辑 =》 职责分明 react库只负责ui渲染
import { AppDispatch } from '@/store'
import { getCodeAction, loginAction } from '@/store/actions/login'
import { getError } from '@/utils/Error'
import { Form, Toast } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'
import { LoginParams } from './index'

export function useLogin() {
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const codeRef = useRef<InputRef>(null)
  let timeLeft = useRef(-1)
  const [time, setTime] = useState(0)
  // 需要将 location的类型断言成 state对象
  const location = useLocation() as { state: { redirectUrl: string } }
  // 加 ？ 是为了放置不是token 失效时跳转取不到值报错
  const redirectUrl = location.state?.redirectUrl
  // console.log(redirectUrl)
  // 登录
  const onFinish = async (value: LoginParams) => {
    console.log(value)
    try {
      await dispatch(loginAction(value))
      Toast.show({
        icon: 'success',
        content: '登录成功',
        position: 'top',
        afterClose: () => navigate(redirectUrl || '/', { replace: true }),
      })
    } catch (error) {
      getError(error)
    }
  }
  // 倒计时函数
  const timeOut = (t: number) => {
    timeLeft.current = window.setTimeout(() => {
      setTime(time - 1)
    }, t * 1000)
    return time < 10 ? '0' + time : time
  }
  useEffect(() => {
    if (time === 0) {
      clearTimeout(timeLeft.current)
    }
  }, [time])
  // 获取验证码
  const getCode = async () => {
    const data = form.getFieldsValue(true)
    const isPass = form.getFieldError('mobile')
    const pass = !!!isPass.length && !(JSON.stringify(data) === '{}')
    if (pass) {
      setTime(59)
      timeOut(1)
      await dispatch(getCodeAction(data.mobile))
      codeRef.current?.focus()
    } else {
      mobileRef.current?.focus()
    }
  }
  // 提供服务
  return { onFinish, getCode, form, mobileRef, time, codeRef, timeOut }
}